import * as net from 'net';
// 定义客户端集合
const clients: Map<string, net.Socket> = new Map();

// 处理创建客户端连接的函数
export function createClient(event: Electron.IpcMainInvokeEvent, clientId: string): string {
  if (clients.has(clientId)) {
    return `${clientId}客户端已连接`;
  }
  const client = new net.Socket();
  client.connect(10000, '127.0.0.1', () => {
    console.log(`客户端 ${clientId} 已连接到服务器`);
    event.sender.send('client-status', `客户端 ${clientId} 已连接到服务器`);
    client.write("clientId:" + clientId);

  });



  client.on('data', (data) => {
    console.log(`客户端 ${clientId} 收到服务端数据:`, data.toString());
    event.sender.send('server-response', { clientId, data: data.toString() });
  });

  client.on('close', () => {
    console.log(`客户端 ${clientId} 连接已关闭`);
    event.sender.send('client-status', `客户端 ${clientId} 连接已关闭`);
    clients.delete(clientId);
  });

  client.on('error', (err) => {
    console.error(`客户端 ${clientId} 错误:`, err);
    event.sender.send('client-status', `客户端 ${clientId} 错误: ${err.message}`);
    clients.delete(clientId);
  });

  clients.set(clientId, client);
  return `客户端 ${clientId} 已创建`;
}

// 处理发送命令的函数
export function sendCommand(_event: Electron.IpcMainInvokeEvent, clientId: string, command: string): string {
  const client = clients.get(clientId);
  if (client) {
    //todo 转成具体的格式；
    testSendCommand(client, command);

    return `命令已发送到客户端 ${clientId}`;
  } else {
    return `客户端 ${clientId} 未连接`;
  }
}

function testSendCommand(client, command) {
  let buffer = Buffer.alloc(0);;
  switch (command) {
    case '1':
      buffer = Buffer.concat([Buffer.from([0x01]), Buffer.from('我是命令1', 'utf8')]);
      break;
    case '2':
      buffer = Buffer.concat([Buffer.from([0x02]), Buffer.from('我是命令2', 'utf8')]);
      break;

    case '3':
      buffer = Buffer.concat([Buffer.from([0x03]), Buffer.from('我是命令3', 'utf8')]);
      break;
    default:
      buffer = Buffer.from(command);
      break
  }
  client.write(buffer);
}